using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
using NPack;

namespace TaskFramework.Tests
{
    public class FetchTradesTask : Task
    {
        private static int _taskCounter;
        private readonly int _myTaskId;
        private readonly MersenneTwister _random = new MersenneTwister(888);
        private readonly FetchTradesRequest _requestData;
        private int _remainingRouteCount;

        public FetchTradesTask(FetchTradesRequest requestData)
        {
            _requestData = requestData;
            _remainingRouteCount = _requestData.RemainingRouteCount;

            _myTaskId = ++_taskCounter;
        }

        public override object RequestData
        {
            get { return _requestData; }
        }

        public override void Execute(RoutingHelper router)
        {
            bool shouldRoute = false;

            lock (this)
            {
                //Debug.WriteLine("FetchTradesTask: Remaining reroute count = " + _remainingRerouteCount);
                if (_remainingRouteCount > 0)
                {
                    shouldRoute = true;
                    _remainingRouteCount--;
                }
            }

            if (shouldRoute)
            {
                if (_requestData.RouteType == RouteType.TransferTaskToPool)
                {
                    router.TransferToPool(this);
                    return;
                }

                if (_requestData.RouteType == RouteType.RouteRequestInBatchAndSetRouteCountToZero)
                {
                    router.RouteRequest(new FetchTradesRequest(_requestData.BatchSize, _remainingRouteCount, _requestData.RouteType, _requestData.MillisecondDelay));
                }
            }

            if (_requestData.MillisecondDelay > 0)
            {
                Thread.Sleep(_requestData.MillisecondDelay);

            }

            if (_requestData.ThrowException)
            {
                throw new InvalidOperationException("Testing...");
            }

            int tradeId = _random.Next(100000, 999999);

            IList trades = new List<Trade>(new[] { new Trade(tradeId) });
            router.SendResult(trades);
        }

        
    }
}